package com.example.mybiadushoujiweishi.activity.acivitys.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;

import com.example.mybiadushoujiweishi.activity.acivitys.entity.Contact;
import com.example.mybiadushoujiweishi.activity.acivitys.entity.MobileInfo;
import com.example.mybiadushoujiweishi.activity.db.MobileInfoDao;
import com.github.lzyzsd.randomcolor.RandomColor;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/17 0017.
 */

public class Myuitl {


    public static boolean isSD() {

        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state))  //判断存储器是否可读写
        {
            return true;
        } else {

            return false;
        }
    }

    public static File getDir() {

        if (isSD()) {
            return Environment.getExternalStorageDirectory();
        }


        return Environment.getDownloadCacheDirectory();

    }


    public static Intent install(File file) {
        System.out.println(file + "    install}}}}}}}}}}}}}}}}}");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        MyApplication.getContext().startActivity(intent);
        return intent;
    }


    public static Drawable getBBXIcon(String functionPic) {
        Context context = MyApplication.getContext();
        int resId = context.getResources().getIdentifier(functionPic, "mipmap", context.getPackageName());

        Drawable drawable = ContextCompat.getDrawable(context, resId);
        return drawable;

    }


    public static void copyFiletoMobile(Context context, String dbname, String newname) throws Exception {

        URL url = context.getClass().getClassLoader().getResource("assets/" + dbname);
        String filedir = "/data/data/" + MyApplication.getContext().getPackageName() + "/databases";
        File fileMobiledir = new File(filedir);
        if (!fileMobiledir.exists()) {
            fileMobiledir.mkdirs();
        }


        //    FileUtils.copyURLToFile(url,dbfileMobile);

        File fileMobile = new File(fileMobiledir + "/" + newname);
        if (!fileMobile.exists()) {
            fileMobile.createNewFile();
        }

        //第一个参数是包含路径源文件，第二参数是
        FileUtils.copyURLToFile(url, fileMobile);

    }

    /**
     * @return 查询联系人
     */
    public static List<Contact> getAllContacts() {
        List<Contact> lists = new ArrayList<Contact>();
        //通过内容提供者查询联系人
//      访问联系人的uri：
//      ContactsContract.Contacts.CONTENT_URI
//      访问电话号码的uri：
//      ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {

                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));//
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));//手机联系人
                int num = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phonenum = null;
                //如果大于0，表示有电话号码
                if (num > 0) {
                    phonenum = getPhonenumByID(id);
                }
                //获取手机归属地？？？
                //准备工作：将外部数据库拷贝到手机中的方法  1、在哪调用方法 MyAppication  2使用greendao框架来调用外部数据库
                String addr = null;
                addr = getAddressByTel(phonenum);
                RandomColor randomColor=new RandomColor();
                int color=randomColor.randomColor();

                Contact contact = new Contact(id, name, phonenum, addr,color);
                lists.add(contact);
            }
            cursor.close();
        }
        return lists;
    }

    /**
     * @param phonenum 获取手机号码
     * @return
     */
    private static String getAddressByTel(String phonenum) {
//        MobileInfo mobileInfo = null;
//        String newtelnumber = phonenum.replace(" ", "").replace("-", "").substring(0, 7);
//        System.out.println(telnumber);
        String newtelnumber = phonenum.replace(" ", "").replace("-", "");
        String telnum = null;
        String address = null;
//        MobileInfo mobileInfo= MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder().
//                where(MobileInfoDao.Properties.MobileNumber.eq(telnumber)).distinct().unique();
        if (newtelnumber.length() == 11 && newtelnumber.matches("^1[3578]\\d{9}$")) {

            telnum = newtelnumber.substring(0, 7);
            address = getAddrBytel(telnum);

        } else {
//            座机号码 3+7 3+8 4+7 4+8
            int length = newtelnumber.length();
            switch (length) {

                case 10:
                  address=  getZuojiByTel(newtelnumber, 3);

                    break;

                case 11:
//                    分两种情况
                    address = getZuojiByTel(newtelnumber, 3);
                    if (address == null) {
                        address = getZuojiByTel(newtelnumber, 4);
                    }

                    break;
                case 12:
                    address = getZuojiByTel(newtelnumber, 4);

                    break;
                default:
                    address="未知";
                    break;

            }
        }


        return address;
    }

    public static String getPhonenumByID(int id) {
        String telnum = null;
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{id + ""}, null);
        if (cursor != null) {
            //我这只取一个电话号码
            if (cursor.moveToNext()) {
                telnum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        cursor.close();

        return telnum;
    }

    /**
     *
     获取座机号码的区号
     */
    public static String getZuojiByTel(String tel, int end) {
        MobileInfo mobileInfo = null;
        mobileInfo = MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(tel.substring(0, end)))
                .limit(1)
                .distinct()
                .unique();

        return mobileInfo.getMobileArea();
    }

    public static String getAddrBytel(String tel) {
        MobileInfo mobileInfo = null;
        mobileInfo = MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel)).distinct().unique();

        return mobileInfo.getMobileArea();
    }

}
